package com.laofang.spring.formework.context.support;

import com.laofang.spring.formework.beans.LFBeanDefinition;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Array;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;

/**对配置文件查找 配置 解析
 * @author ：laofang
 * @date ：Created in 2021/3/30 16:57
 */
public class LFBeanDefinitionReader {

    private List<String> registerBeanClass=new ArrayList<>();

    private Properties config=new Properties();

    //固定配置文件中的key，相当于XML规范
    private final String SCAN_PACKAGE="scanPackage";

    public LFBeanDefinitionReader(String[] configLocations) {
        try(InputStream in = Thread.currentThread().getContextClassLoader().
                getResourceAsStream(configLocations[0].replace("classpath:", ""));) {
            config.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
        doScanner(config.getProperty(SCAN_PACKAGE));
    }

    private void doScanner(String scanPackage) {
        URL url = Thread.currentThread().getContextClassLoader().
                getResource(scanPackage.replace(".", "/"));
        File classPath = new File(url.getFile());
        for (File file : classPath.listFiles()) {
            if (file.isDirectory()) {
                doScanner(scanPackage+file.getName());
            }else{
                if (!file.getName().endsWith(".class")) {
                    continue;
                }
                String className = scanPackage + "." + file.getName().replace(".class", "");
                registerBeanClass.add(className);
            }
        }
    }

    public List<LFBeanDefinition> loadBeanDefinitions() {
        ArrayList<LFBeanDefinition> result = new ArrayList<>();
        try {
            for (String beanClass : registerBeanClass) {
                Class<?> bClass = Class.forName(beanClass);
                if (bClass.isInterface()) {
                    continue;
                }
               String normalName= toLowerFirstCase(bClass.getSimpleName());
                result.add(doCreateBeanDefinition(normalName,bClass.getName()));
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return result;
    }

    private LFBeanDefinition doCreateBeanDefinition(String normalName, String className) {
        LFBeanDefinition definition = new LFBeanDefinition();
        definition.setBeanClassName(className);
        definition.setFactoryBeanName(normalName);
        return definition;
    }

    //将类首字母改为小写
    //为简化程序，就不做判断了
    private String toLowerFirstCase(String simpleName) {
        char[] chars = simpleName.toCharArray();
        //因为大小写字符的ASCII码相差32，且大写的值要小
        chars[0]+=32;
        return String.valueOf(chars);
    }

    public Properties getConfig() {
        return this.config;
    }
}
